//
//  BaseAds.m
//  PaintWar
//
//  Created by Tai Le on 10/9/14.
//
//

#import "BaseAds.h"

@implementation BaseAds

- (id)init
{
    if (self = [super init])
    {
        [self resetConfigure];
        [self startThreadCheckTimeOut];
    }
    
    return self;
}

- (void)startThreadCheckTimeOut
{
    _threadStatus = ThreadRun;
    NSInteger timeOut = ADSMIX_TIME_OUT;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        while (_threadStatus != ThreadStop)
        {
            [NSThread sleepForTimeInterval:1];
            
            if (_threadStatus == ThreadPause)
            {
                continue;
            }
            
            _countSeconds++;
            
            NSLog(@"[%@] Check time out %d/%d", self.class, _countSeconds, timeOut);
            
            if (_countSeconds > timeOut)
            {
                NSMutableDictionary* details = [NSMutableDictionary dictionary];
                [details setValue:@"Request time out" forKey:NSLocalizedDescriptionKey];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    //force change to next request
                    [self raiseDidFail:[self getAds] error:[NSError errorWithDomain:@"AdsMix" code:0 userInfo:details] isGoToNextAds:YES];
                });                
            }
            
        }
    });
}

- (void)dealloc
{
    _threadStatus = ThreadStop;
}

- (BOOL)isOutOfFail
{
    if (_adMixType == AdMixTypeWeight)
    {
        if (_countRequestFail >= _numberOfAllowFails)
        {
            return true;
        }
    }
    else if (_adMixType == AdMixTypePeriod)
    {
        NSInteger diffSeconds = (_timeLastRequest - _timeFirstRequest);
        if (diffSeconds > _period)
        {
            return true;
        }
    }
    
    return false;
}

- (BOOL)showAdInterstitialInViewController:(UIViewController *)controller
{
    return NO;
}

- (BOOL)showAdInterstitialInView:(UIView *)view
{
    return NO;
}

- (id)getAds
{
    return nil;
}

- (void)releaseAds
{
    _threadStatus = ThreadStop;
}

- (void)resetConfigure
{
    _countRequestFail = 0;
    _timeFirstRequest = [[NSDate date] timeIntervalSince1970];
    _timeLastRequest = 0;
}

- (void)raiseDidLoad:(id)ads
{
    if ([[self getAds] isEqual:ads] == NO)
    {
        NSLog(@"[%@]Ignore DidLoad", [ads class]);
        
        return;
    }
    
    if (_isAdsVisible)
    {
        NSLog(@"[%@] was visible", [ads class]);
        return;
    }
    
    _isAdsVisible = YES;
    _threadStatus = ThreadPause;
    
    [self resetConfigure];
    [self resetCountSeconds];
    
    if ([_delegate respondsToSelector:@selector(adsDidLoad:)])
    {
        [_delegate adsDidLoad:self];
    }
}

- (void)raiseDidUnload:(id)ads
{
    if ([[self getAds] isEqual:ads] == NO)
    {
        NSLog(@"[%@]Ignore DidUnload", [ads class]);
        
        return;
    }
    
    _isAdsVisible = NO;
    _threadStatus = ThreadPause;
    
    [self releaseAds];
    [self resetConfigure];
    [self resetCountSeconds];
    
    if ([_delegate respondsToSelector:@selector(adsDidUnload:)])
    {
        [_delegate adsDidUnload:self];
    }
}

- (void)raiseDidFail:(id)ads error:(NSError *)error
{
    [self raiseDidFail:ads error:error isGoToNextAds:NO];
}

- (void)raiseDidFail:(id)ads error:(NSError *)error isGoToNextAds:(BOOL)isGoToNextAds
{
    if ([[self getAds] isEqual:ads] == NO)
    {
        NSLog(@"[%@]Ignore DidFail", [ads class]);
        
        return;
    }
    
    _isAdsVisible = NO;
    _threadStatus = ThreadPause;
    if (isGoToNextAds)
    {
        _countRequestFail = _numberOfAllowFails;
        _timeLastRequest = _timeFirstRequest + _period + 5;
    }
    else
    {
        _countRequestFail++;
        _timeLastRequest = [[NSDate date] timeIntervalSince1970];
    }
    
    [self resetCountSeconds];
    
    NSLog(@"[%@] fail: %@", self.class, error);
    
    if ([_delegate respondsToSelector:@selector(adsDidFail:withError:)])
    {
        [_delegate adsDidFail:self withError:error];
    }
}

- (void)cycleAds
{
    _isAdsVisible = NO;
    _threadStatus = ThreadRun;
    
    [self resetCountSeconds];
    
    NSLog(@"[%@] try to request at time %ld",[self class], (_countRequestFail + 1));
}

- (void)resetCountSeconds
{
    _countSeconds = 0;
}

@end
